package org.best.practices.android.rotationasynctask.task;

import android.os.AsyncTask;
import android.os.SystemClock;
import android.util.Log;

public class LongOperationAsyncTask extends AsyncTask<Void, Void, Void> implements ProgressCallbackProvider {
    private final static String TAG = LongOperationAsyncTask.class.getSimpleName();
    
    private int mOperationStep = 0;
	private int mOperationSteps = 50;
	private int mOperationTimeout = 500;
	
	private OnProgressOperationListener mProgressListener = new DefaultProgressListener();
	
	public LongOperationAsyncTask(int steps, int timeout) {
        super();
        this.mOperationSteps = steps;
        this.mOperationTimeout = timeout;
    }

    public LongOperationAsyncTask() {}

    @Override
	protected Void doInBackground(Void... params) {
		
		for (mOperationStep = 1; mOperationStep < mOperationSteps; mOperationStep++) {
			SystemClock.sleep(mOperationTimeout);
			mProgressListener.onProgressOperationStep(mOperationStep, mOperationSteps);
		}
		// invokes a callback after a long operation
		mProgressListener.onProgressOperationFinished();
		
		return(null);
	}
	
	private class DefaultProgressListener implements OnProgressOperationListener {
        @Override
        public void onProgressOperationStep(int completed, int total) {
            Log.d(TAG, String.format("DefaultLongOperationListener onProgressOperationStep %d / %d", completed, total));
        }

        @Override
        public void onProgressOperationFinished() {
            Log.d(TAG, "DefaultLongOperationListener onLongOperationFinish");
        }	    
	}

    @Override
    public void setOnProgressListener(OnProgressOperationListener listener) {
        mProgressListener = listener;
        // there is a chance the task will finish while activity is recreated
        mProgressListener.onProgressOperationStep(mOperationStep, mOperationSteps);
    }

    @Override
    public void removeOnProgressListener() {
        mProgressListener = new DefaultProgressListener();
    }
}
